package com.ncmmall.application.util.code;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

/**
 * Created by EDZ on 2018/6/22.
 */
public class QRCodeFactory {

    /**
     * 给生成的二维码添加中间的logo
     *
     * @param matrixImage 生成的二维码
     * @param logUri      logo地址
     * @return 带有logo的二维码
     * @throws IOException logo地址找不到会有io异常
     */
    public BufferedImage setMatrixLogo(BufferedImage matrixImage, String logUri) throws IOException {
        /**
         * 读取二维码图片，并构建绘图对象
         */
        Graphics2D g2 = matrixImage.createGraphics();
        int matrixWidth = matrixImage.getWidth();
        int matrixHeigh = matrixImage.getHeight();

        /**
         * 读取Logo图片
         */
        BufferedImage logo = ImageIO.read(new File(logUri));

        //开始绘制图片
        g2.drawImage(logo, matrixWidth / 5 * 2, matrixHeigh / 5 * 2, matrixWidth / 5, matrixHeigh / 5, null);
        //绘制边框
        BasicStroke stroke = new BasicStroke(5, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        // 设置笔画对象
        g2.setStroke(stroke);
        //指定弧度的圆角矩形
        RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth / 5 * 2, matrixHeigh / 5 * 2, matrixWidth / 5, matrixHeigh / 5, 20, 20);
        g2.setColor(Color.white);
        // 绘制圆弧矩形
        g2.draw(round);

        //设置logo 有一道灰色边框
        BasicStroke stroke2 = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        // 设置笔画对象
        g2.setStroke(stroke2);
        RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth / 5 * 2 + 2, matrixHeigh / 5 * 2 + 2, matrixWidth / 5 - 4, matrixHeigh / 5 - 4, 20, 20);
        g2.setColor(new Color(128, 128, 128));
        g2.draw(round2);// 绘制圆弧矩形

        g2.dispose();
        matrixImage.flush();
        return matrixImage;
    }

    /**
     * 创建我们的二维码图片
     *
     * @param content 二维码内容
     * @param size    用于设定图片大小（可变参数，宽，高）
     * @throws IOException     抛出io异常
     * @throws WriterException 抛出书写异常
     */
    public static String creatQrImage(String content, int... size) throws IOException, WriterException {
        int width = 172; // 二维码图片宽度 172
        int height = 172; // 二维码图片高度172

        //如果存储大小的不为空，那么对我们图片的大小进行设定
        if (size.length == 2) {
            width = size[0];
            height = size[1];
        } else if (size.length == 1) {
            width = height = size[0];
        }

        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        // 指定纠错等级,纠错级别（L 7%、M 15%、Q 25%、H 30%）
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        // 内容所使用字符集编码
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //hints.put(EncodeHintType.MAX_SIZE, 350);//设置图片的最大值
        //hints.put(EncodeHintType.MIN_SIZE, 100);//设置图片的最小值
        hints.put(EncodeHintType.MARGIN, 1);//设置二维码边的空度，非负数

        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,//要编码的内容
                //编码类型，目前zxing支持：Aztec 2D,CODABAR 1D format,Code 39 1D,Code 93 1D ,Code 128 1D,
                //Data Matrix 2D , EAN-8 1D,EAN-13 1D,ITF (Interleaved Two of Five) 1D,
                //MaxiCode 2D barcode,PDF417,QR Code 2D,RSS 14,RSS EXPANDED,UPC-A 1D,UPC-E 1D,UPC/EAN extension,UPC_EAN_EXTENSION
                BarcodeFormat.QR_CODE,
                width, //条形码的宽度
                height, //条形码的高度
                hints);//生成条形码时的一些配置,此项可选

        return MatrixToImageWriter.writeToFile(bitMatrix);
    }

//    /**
//     * 生成商家二维码
//     */
//    private void createQrcode(String subject) {
//
//        try {
//            File qrPic = QRCode.from(subject).to(ImageType.JPG).withSize(500, 500).withErrorCorrection(ErrorCorrectionLevel.H).file();
//
//            BufferedImage image = ImageIO.read(qrPic);
//            Graphics2D g = image.createGraphics();
//
//            //读取用户头像
//            BufferedImage logo = ImageIO.read(new File(PropertiesHelps.getValue("store.path") + File.separator + "avatar" + File.separator + user.getAvatar()));
//            //设置头像的大小
//            int widthLogo = logo.getWidth(null) > image.getWidth() * 2 / 10 ? (image.getWidth() * 2 / 10) : logo.getWidth(null);
//            int heightLogo = logo.getHeight(null) > image.getHeight() * 2 / 10 ? (image.getHeight() * 2 / 10) : logo.getHeight(null);
//
//            // 计算图片放置位置，默认在中间
//            int x = (image.getWidth() - widthLogo) / 2;
//            int y = (image.getHeight() - heightLogo) / 2;
//
//            // 开始绘制图片
//            g.drawImage(logo, x, y, widthLogo, heightLogo, null);
//            g.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);
//            //边框宽度
//            g.setStroke(new BasicStroke(2));
//            //边框颜色
//            g.setColor(Color.WHITE);
//            g.drawRect(x, y, widthLogo, heightLogo);
//
//            g.dispose();
//            logo.flush();
//
//            image.flush();
//            String fileName = Joiner.on(".").join(new Date().getTime(), "jpg");
//            String path = PropertiesHelps.getValue("store.path") + File.separator + "qrCodes";
//            File dirPath = new File(path);
//            if (!dirPath.exists()) {
//                dirPath.mkdir();
//            }
//            FileInputStream fis = new FileInputStream(qrPic);
//            ByteArrayOutputStream bos = new ByteArrayOutputStream();
//            byte[] b = new byte[1024];
//            int n;
//            while ((n = fis.read(b)) != -1) {
//                bos.write(b, 0, n);
//            }
//            fis.close();
//            bos.close();
//            byte[] buffer = bos.toByteArray();
//            File storeFile = new File(Joiner.on(File.separator).join(path, fileName, new Object[0]));
//            FileCopyUtils.copy(buffer, storeFile);
//            ImageIO.write(image, "jpg", storeFile);
//            BusinessInfo businessInfo = user.getBusinessInfo();
//            businessInfoApplication.saveQRCode(fileName, businessInfo);
//        } catch (Exception e) {
//            log.error("[生成商家二维码异常]", e);
//        }
//    }
}
